var express = require('express')
var User = require('./user')
var md5 = require('blueimp-md5')

var router = express.Router()
router.get('/', function (req, res) {
    res.render('index.html', {
        user: req.session.user
    })
})
//渲染注册页面
router.get('/register', function (req, res) {
    res.render('register.html')
})
//处理注册请求数据
router.post('/register', function (req, res) {
    var body = req.body
    User.findOne({
        $or: [{ email: body.email }, { nickname: body.nickname }]
    }, function (err, user) {
        if (err) {
            return res.status(500).json({
                err_code: 500,
                message: err.message
            })
        }
        if (user) {
            return res.status(200).json({
                err_code: 1,
                message: 'email or password invalid'
            })
        }
        //保存到数据库
        body.password = md5(md5(body.password))
        new User(body).save(function (err, user) {
            if (err) {
                return res.status(500).json({
                    err_code: 500,
                    message: err.message
                })
            }
            req.session.user = user
            res.status(200).json({
                err_code: 0,
                message: 'register success'
            })

        })
    })
})
// 渲染登录页面
router.get('/login', function (req, res) {
    res.render('login.html')
})
router.post('/login', function (req, res) {
    var body = req.body
    User.findOne({
        email: body.email, password: md5(md5(body.password))
    }, function (err, user) {
        if (err) {
            return res.status(500).json({
                err_code: 500,
                message: err.message
            })
        }
        if (!user) {
            return res.status(500).json({
                err_code: 1,
                message: 'email or password invalid'
            })
        }
        req.session.user = user
        res.status(200).json({
            err_code: 0,
            message: "login success"
        })

    })
})
//退出登录
router.get('/logout', function (req, res) {
    req.session.user=null;
    
    res.redirect('/')
    console.log(req.session.user);
})
module.exports = router